<?php
/*
Copyright 2008, Nathalia


Author:
Nathalia Sautchuk Patrício          (nathalia.sautchuk@gmail.com)

*/
class Listar extends TPage
{
	public function onInit($param)
    {
        parent::onInit($param);

        if($this->Request['all'] == 1)
            $this->Titulo->Text = 'Todas os Artigos';
        else
            $this->Titulo->Text = 'Meus Artigos';
        
        if($this->Request['status'] == 0)
            $this->Titulo->Text = $this->Titulo->Text.' Em Avalia&ccedil;&atilde;o';
        else if($this->Request['status'] == 1)
            $this->Titulo->Text = $this->Titulo->Text.' Aprovados';
        else if($this->Request['status'] == 2)
            $this->Titulo->Text = $this->Titulo->Text.' Reprovados';

        if(!$this->IsPostBack)  // if the page is requested the first time
        {
            // get the total number of posts available
            $this->Repeater->VirtualItemCount = ArtigoRecord::finder()->count();
            // populates post data into the repeater
            $this->populateData();
        }
    }
 
    public function pageChanged($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData();
    }
 
    protected function populateData()
    {
        $offset = $this->Repeater->CurrentPageIndex * $this->Repeater->PageSize;
        $limit  = $this->Repeater->PageSize;
        if($offset+$limit > $this->Repeater->VirtualItemCount)
            $limit = $this->Repeater->VirtualItemCount - $offset;
        $this->Repeater->DataSource = $this->getArtigos($offset,$limit);
        $this->Repeater->dataBind();
    }

    protected function getArtigos($offset, $limit)
    {   
        $criteria                       = new TActiveRecordCriteria;
        //$criteria->Limit                = $limit;
        //$criteria->Offset               = $offset;
        
        if(!$this->Request['status'])
            $this->Request['status'] = 0;

        if($this->Request['all'] == 1)
        {
            $criteria->OrdersBy['ArtigoID'] = 'asc';
            $criteria->Condition = 'Status = '.$this->Request['status'];
            // query for the posts with the above criteria and with author information
            return ArtigoRecord::finder()->findAll($criteria);
        }
        else
        {
            $criteria->Condition = 'UsuarioID = '.$this->User->Name;
            $autores = UserRecord::finder()->withArtigos('Status = '.$this->Request['status'])->findAll($criteria);

            return $autores[0]->artigos;
        }
    }

}
?>
